package com.inossem.warehousestorage_inossem.activity.inventory;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.utils.log.LogUtils;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryAreaBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryIntegrationBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryNewMatQueryReqBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryOrdinaryMatReqBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryOrdinaryMaterieBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryRespBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.request.inventory.InventoryManageRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.InventoryUtils;
import com.inossem.warehousestorage_inossem.utils.SPUtils;
import com.zhy.android.percent.support.PercentRelativeLayout;

import java.util.List;

import static com.inossem.utils.constant.QRCodeConstant.TYPE_BATCH;

public class InventoryItemActivity extends BaseActivity {

    //增加，下一个标识
    private static final int TYPE_ADD = 1;

    //减少，上一个标识
    private static final int TYPE_REDUCE = 2;

    //退出仓位标识
    private static final int TYPE_BACK = 3;

    //改变仓位标识
    private static final int TYPE_CHANGE = 4;

    //标识仓位中物料起始
    private static final int FLAG_BEGIN = 1;

    //标识仓位中物料结尾
    private static final int FLAG_END = 2;

    private TextView title;

    private TextView total, materielCode, positionNumber, number, inventoryNumber, materielDescription, specialInventoryFlagValue, specialInventoryDescription, batch, specialInventoryCode, unit;

    //下一个，上一个，返回按钮
    private Button nextItem, preItem, back;

    private int index = 0;

    private String mRetainDecimal;

    //    private InventoryOverviewBean.DataBean overviewBean;
    private InventoryOrdinaryMaterieBean.DataBean bean;
    private List<InventoryOrdinaryMaterieBean.DataBean.ItemListBean> items;
    private InventoryAreaBean areaBean;
    private InventoryOrdinaryMaterieBean.DataBean.ItemListBean item;
    private PercentRelativeLayout bottom, row6;

    //存储发请求获取仓位下所有物料的参数
    private InventoryNewMatQueryReqBean querybean;

    //标识是结尾还是开头
    private int flag = 0;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_inventory_item);
        initView(InventoryItemActivity.this);
        initData(InventoryItemActivity.this);
    }


    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        total = (TextView) activity.findViewById(R.id.total);
        preItem = (Button) activity.findViewById(R.id.preItem);
        nextItem = (Button) activity.findViewById(R.id.nextItem);
        back = (Button) activity.findViewById(R.id.back);

        materielCode = (TextView) activity.findViewById(R.id.materielCode);
        positionNumber = (TextView) activity.findViewById(R.id.positionNumber);
        number = (TextView) activity.findViewById(R.id.number);
        inventoryNumber = (TextView) activity.findViewById(R.id.inventoryNumber);
        materielDescription = (TextView) activity.findViewById(R.id.materielDescription);
        specialInventoryFlagValue = (TextView) activity.findViewById(R.id.specialInventoryFlagValue);
        specialInventoryDescription = (TextView) activity.findViewById(R.id.specialInventoryDescription);
        batch = (TextView) activity.findViewById(R.id.batch);
        specialInventoryCode = (TextView) activity.findViewById(R.id.specialInventoryCode);
        unit = (TextView) activity.findViewById(R.id.unit);

        bottom = (PercentRelativeLayout) activity.findViewById(R.id.bottom);
        row6 = (PercentRelativeLayout) activity.findViewById(R.id.row6);

    }

    private void initData(Activity activity) {
        title.setText(activity.getResources().getString(R.string.activity_inventory_item_title));
        ActivityUtils.initBackAndFunction(activity, activity.getResources().getString(R.string.activity_inventory_overview_title), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                goAndUpdate(activity, TYPE_BACK);
            }
        });
        nextItem.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if ((index + 1) > (items.size() - 1)) {
//                    InventoryNewMatQueryReqBean tempBean = getChangeInventoryNewMatQueryReqBean(activity, querybean, TYPE_ADD);
//                    if (tempBean != null) {
//                        querybean = tempBean;
//                        flag = FLAG_BEGIN;
//                        goAndUpdate(activity, TYPE_CHANGE);
//                    } else {
                        Utils.middleToast(activity, getResources().getString(R.string.activity_inventory_item_to_end));
//                    }
                } else {
                    changeAndSet(activity, TYPE_ADD);
                }

            }
        });

        preItem.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index - 1 < 0) {
                    InventoryNewMatQueryReqBean tempBean = getChangeInventoryNewMatQueryReqBean(activity, querybean, TYPE_REDUCE);
                    if (tempBean != null) {
                        querybean = tempBean;
                        flag = FLAG_END;
                        goAndUpdate(activity, TYPE_CHANGE);
                    } else {
                        Utils.middleToast(activity, getResources().getString(R.string.activity_inventory_item_to_begin));
                    }
                } else {
                    changeAndSet(activity, TYPE_REDUCE);
                }
//                if (!TextUtils.isEmpty(number.getText().toString()) && !RegexUtils.checkDecimal(number.getText().toString())) {
//                    Utils.middleToast(activity, "实盘数量不合法");
//                    return;
//                } else {
//                    InventoryItemActivity.this.index--;
//                    item.setNumber(number.getText().toString());
//                    load();
//                }
            }
        });

//        this.number.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//            }
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                LogUtils.i("111");
//                //不然每次输入，都会调用一次set方法
//                if (getCurrentFocus() == number) {
//                    LogUtils.i("222");
//                    item.setNumber(number.getText().toString());
//
//                }
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
//
//            }
//        });

        back.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                goAndUpdate(activity, TYPE_BACK);
            }
        });
        setmScanListener((String scanResult, int length) -> {
            String materielCode = "";
            String type = QRCodeUtils.getQRCodeType(scanResult);
            if (TYPE_BATCH.equals(type)) {
                materielCode = QRCodeUtils.DecryptQRCode(scanResult, QRCodeConstant.PARAMETER_MATERIEL_CODE);
            } else if (QRCodeConstant.TYPE_MATERIEL_CODE.equals(type)) {
                materielCode = QRCodeUtils.DecryptQRCode(scanResult);
            }
            boolean flag = findMaterielCode(materielCode);
            if (flag) {
                load();
            } else {
                Utils.middleToast(activity, getResources().getString(R.string.activity_inventory_material_is_not_found_in_this_position) + materielCode + getResources().getString(R.string.activity_inventory_material_this_material));
            }
        }, TYPE_BATCH, QRCodeConstant.TYPE_MATERIEL_CODE);
        areaBean = SPUtils.getInformation(activity, InventoryAreaBean.class, SPUtils.KEY_INVENTORY_INFORMATION);
        querybean = getInitInventoryNewMatQueryReqBean(activity);
        getData(activity, querybean);
    }

    private InventoryNewMatQueryReqBean getInitInventoryNewMatQueryReqBean(Activity activity) {
        String areaNumberValue = activity.getIntent().getStringExtra(InventoryExtra.AREA_NUMBER_VALUE);
        String positionNumberValue = activity.getIntent().getStringExtra(InventoryExtra.POSITION_NUMBER_VALUE);
        InventoryNewMatQueryReqBean result = new InventoryNewMatQueryReqBean();
        result.setAreaNumberValue(areaNumberValue);
        result.setPositionNumberValue(positionNumberValue);
        result.setInventoryVoucher(areaBean.getInventoryVoucher());
        return result;
    }

    private InventoryNewMatQueryReqBean getChangeInventoryNewMatQueryReqBean(Activity activity, InventoryNewMatQueryReqBean queryBean, int type) {
        InventoryNewMatQueryReqBean result = null;
        Gson gson = new Gson();
        List<InventoryIntegrationBean.InventoryListBean> inventoryList = gson.fromJson(SPUtils.getInventoryIntegrationInformation(activity), InventoryIntegrationBean.class).getInventoryList();
        int inventoryListSize = inventoryList.size();
        int beanIndex = -1;
        for (int i = 0; i < inventoryListSize; i++) {
            InventoryIntegrationBean.InventoryListBean inventoryBean = inventoryList.get(i);
            if (inventoryBean.getAreaNumberValue().equals(queryBean.getAreaNumberValue()) && inventoryBean.getPositionNumberValue().equals(queryBean.getPositionNumberValue()) && inventoryBean.getInventoryVoucher().equals(queryBean.getInventoryVoucher())) {
                beanIndex = i;
                break;
            }
        }
        switch (type) {
            case TYPE_ADD:
                beanIndex++;
                LogUtils.i("beanIndex ==== " + beanIndex + "inventoryListSize ===== " + inventoryListSize);
                if (beanIndex > inventoryListSize || beanIndex == inventoryListSize) {
                    return result;
                } else {
                    InventoryIntegrationBean.InventoryListBean addResultInventoryBean = inventoryList.get(beanIndex);
                    result = new InventoryNewMatQueryReqBean();
                    result.setInventoryVoucher(addResultInventoryBean.getInventoryVoucher());
                    result.setAreaNumberValue(addResultInventoryBean.getAreaNumberValue());
                    result.setPositionNumberValue(addResultInventoryBean.getPositionNumberValue());
                }
                break;
            case TYPE_REDUCE:
                beanIndex--;
                if (beanIndex < 0) {
                    return result;
                } else {
                    InventoryIntegrationBean.InventoryListBean addResultInventoryBean = inventoryList.get(beanIndex);
                    result = new InventoryNewMatQueryReqBean();
                    result.setInventoryVoucher(addResultInventoryBean.getInventoryVoucher());
                    result.setAreaNumberValue(addResultInventoryBean.getAreaNumberValue());
                    result.setPositionNumberValue(addResultInventoryBean.getPositionNumberValue());
                }
                break;
        }
        return result;
    }

//    private InventoryNewMatQueryReqBean getInventoryNewMatQueryReqBean(Activity activity, boolean isInit, int... type) {
//        if (isInit) {
//            String areaNumberValue = activity.getIntent().getStringExtra(InventoryExtra.AREA_NUMBER_VALUE);
//            String positionNumberValue = activity.getIntent().getStringExtra(InventoryExtra.POSITION_NUMBER_VALUE);
//            InventoryNewMatQueryReqBean query = new InventoryNewMatQueryReqBean();
//            query.setAreaNumberValue(areaNumberValue);
//            query.setPositionNumberValue(positionNumberValue);
//            query.setInventoryVoucher(areaBean.getInventoryVoucher());
//            return query;
//        } else {
//            Gson gson = new Gson();
//            InventoryIntegrationBean inventoryIntegrationBean = gson.fromJson(SPUtils.getInventoryIntegrationInformation(activity), InventoryIntegrationBean.class);
//
//            return null;
//        }
//    }

//    private void goBack() {
//
//        goAndUpdate(InventoryItemActivity.this, TYPE_BACK);
//
//        if (!TextUtils.isEmpty(number.getText().toString()) && !RegexUtils.checkDecimal(number.getText().toString())) {
//            Utils.middleToast(this, "实盘数量不合法");
//            return;
//        }
//        InventoryOrdinaryMatReqBean imrb = InventoryUtils.genUpdateItems(this.bean);
//        if (imrb.getMaterielList().size() > 0) {
//
//            InventoryManageRequest.updateItems(this, imrb, new GsonBeanListener<InventoryRespBean>() {
//                @Override
//                public void onSuccess(InventoryRespBean bean) {
//                    if (bean.getData().getCode().equals(RequestConstant.BEAN_CODE_SUCCESS)) {
//                        finish();
//                    } else {
//                        Utils.middleToast(InventoryItemActivity.this, bean.getData().getMsg());
//                    }
//
//
//                }
//            });
//        } else {
//            DialogUtils.getConfirmDialog(this, "实盘数量没有填写，退出将不保存任何信息", new DialogUtils.ConfirmDialogListener() {
//                @Override
//                public void onConfirm(Dialog dialog) {
//                    finish();
//                }
//            }).show();
//
//        }
//
//    }

    private void getData(Activity activity, InventoryNewMatQueryReqBean query) {
        InventoryManageRequest.findOrdList(activity, query, new GsonBeanListener<InventoryOrdinaryMaterieBean>() {
            @Override
            public void onSuccess(InventoryOrdinaryMaterieBean bean) {
                items = bean.getBody().getItem_list();
                InventoryItemActivity.this.bean = bean.getBody();
                switch (flag) {
                    case FLAG_BEGIN:
                        index = 0;
                        break;
                    case FLAG_END:
                        index = items.size() - 1;
                        break;
                }
                load();
            }
        });
    }


    private void load() {
        if (items == null || items.isEmpty()) {
            Utils.middleToast(this, getResources().getString(R.string.activity_inventory_material_data_load_exception));
            finish();
            return;
        }
        item = items.get(index);
        //判断是否显示库存数量，明盘显示
        if (InventoryUtils.isWhite(areaBean)) {
            row6.setVisibility(View.VISIBLE);
        }

        materielCode.setText(item.getMat_code());
        positionNumber.setText(bean.getPosition_code());
        number.setText(item.getStocktake_qty());
        mRetainDecimal = item.getDecimal_place();
        inventoryNumber.setText(item.getStock_qty() + item.getUnit_name());
        materielDescription.setText(item.getMat_name());
        if (!TextUtils.isEmpty(item.getSpec_stock())) {
            specialInventoryFlagValue.setText(item.getSpec_stock() + "-" + item.getSpec_stock_desc());
        }
        specialInventoryDescription.setText(item.getSpec_stock_name());
        batch.setText(item.getBatch());
        this.specialInventoryCode.setText(item.getSpec_stock_code());

        total.setText(index + 1 + "/" + items.size());
        unit.setText(item.getUnit_name());

//        if (items.size() > 1) {
//            this.bottom.setVisibility(View.VISIBLE);
//            if (index == 0) {
//                preItem.setVisibility(View.INVISIBLE);
//                nextItem.setVisibility(View.VISIBLE);
//            } else if (index == items.size() - 1) {
//                nextItem.setVisibility(View.INVISIBLE);
//                preItem.setVisibility(View.VISIBLE);
//            } else {
//                nextItem.setVisibility(View.VISIBLE);
//                preItem.setVisibility(View.VISIBLE);
//            }
//        } else {
//            this.bottom.setVisibility(View.GONE);
//        }

    }

    @Override
    public void onBackPressed() {
        goAndUpdate(InventoryItemActivity.this, TYPE_BACK);
    }

    private String check() {
        String result = null;

        String numberStr = number.getText().toString();
        if (TextUtils.isEmpty(numberStr)) {
            return getResources().getString(R.string.activity_inventory_material_the_number_of_firm_offers_cannot_be_considered_empty);
        }

        if (!RegexUtils.checkDecimal(numberStr)) {
            return getResources().getString(R.string.activity_inventory_the_number_of_firm_offers_is_illegal);
        }
        if (!TextUtils.isEmpty(numberStr) &&!Utils.checkRetainDecimal(numberStr, mRetainDecimal)) {
//            Utils.middleToast(context, context.getResources().getString(R.string.activity_in_storage_receive_overview_serial) + (i + 1) + );
            return String.format(getResources().getString(R.string.common_retain_decimal_illegal), TextUtils.isEmpty(mRetainDecimal) ? getResources().getString(R.string.common_retain_decimal_unlimited) : mRetainDecimal);
        }
//        if (RegexUtils.checkZero(numberStr)) {
//            return "实盘数量必须大于0";
//        }

        return result;
    }

    private void goAndUpdate(Activity activity, int type) {
        String checkResult = check();
        if (checkResult == null) {
            String numberStr = number.getText().toString();
            item.setNumber(numberStr);
            update(activity, type);
        } else {
            String message = "";
            switch (type) {
                case TYPE_BACK:
                    message = getResources().getString(R.string.activity_inventory_item_exit);
                    break;
                case TYPE_CHANGE:
                    message = getResources().getString(R.string.activity_inventory_item_toggle);
                    break;
            }
            DialogUtils.getConfirmDialog(activity, checkResult + "\n" + getResources().getString(R.string.activity_inventory_item_whether_or_not_mandatory) + message, new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    update(activity, type);
                }
            }).show();
        }
    }

    private void update(Activity activity, int type) {
        InventoryOrdinaryMatReqBean imrb = InventoryUtils.genUpdateItems(bean);
        int submitSize = imrb.getItem_list().size();
        int allSize = items.size();
        //判断盘点物料数量是否和当前仓位所有物料数量相等
        if (submitSize == allSize && submitSize > 0) {
            InventoryManageRequest.updateItems(activity, imrb, new GsonBeanListener<InventoryRespBean>() {
                @Override
                public void onSuccess(InventoryRespBean bean) {
//                    if (bean.getData().getCode().equals(RequestConstant.BEAN_CODE_SUCCESS)) {
                        switch (type) {
                            case TYPE_BACK:
                                finish();
                                break;
                            case TYPE_CHANGE:
                                getData(activity, querybean);
                                break;
                        }
//                    } else {
//                        Utils.middleToast(activity, bean.getData().getMsg());
//                    }
                }

                @Override
                public void onFailing(InventoryRespBean bean) {
                    if (!TextUtils.isEmpty(bean.getHead().getMsg())) {
                        Utils.middleToast(activity, bean.getHead().getMsg());
                    }
                }
            });
        } else if (submitSize < allSize && submitSize > 0) {
            //盘点物料数量小于当前仓位所有物料数量时弹出确认框
            String message = "";
            switch (type) {
                case TYPE_BACK:
                    message = getResources().getString(R.string.activity_inventory_item_exit);
                    break;
                case TYPE_CHANGE:
                    message = getResources().getString(R.string.activity_inventory_item_toggle);
                    break;
            }
//            DialogUtils.getConfirmDialog(activity, "当前仓位尚有" + (allSize - submitSize) + "个物料未盘点" + "\n" + "是否强制" + message,
                    DialogUtils.getConfirmDialog(activity, getResources().getString(R.string.activity_inventory_item__position_is_still) + (allSize - submitSize) + getResources().getString(R.string.activity_inventory_item_no_stock_taking) + "\n" +getResources().getString(R.string.activity_inventory_item_whether_or_not_mandatory) + message,
                            new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    InventoryManageRequest.updateItems(activity, imrb, new GsonBeanListener<InventoryRespBean>() {
                        @Override
                        public void onSuccess(InventoryRespBean bean) {
//                            if (bean.getData().getCode().equals(RequestConstant.BEAN_CODE_SUCCESS)) {
                                switch (type) {
                                    case TYPE_BACK:
                                        finish();
                                        break;
                                    case TYPE_CHANGE:
                                        getData(activity, querybean);
                                        break;
                                }
//                            } else {
//                                Utils.middleToast(activity, bean.getData().getMsg());
//                            }
                        }

                        @Override
                        public void onFailing(InventoryRespBean bean) {
                            if (!TextUtils.isEmpty(bean.getHead().getMsg())) {
                                Utils.middleToast(activity, bean.getHead().getMsg());
                            }

                        }
                    });
                }
            }).show();
        } else if (submitSize == 0) {
            //未盘点任何物料
            String message = "";
            switch (type) {
                case TYPE_BACK:
                    message = getResources().getString(R.string.activity_inventory_item_exit);
                    break;
                case TYPE_CHANGE:
                    message = getResources().getString(R.string.activity_inventory_item_toggle);
                    break;
            }
//            DialogUtils.getConfirmDialog(activity, "当前仓位尚有" + (allSize - submitSize) + "个物料未盘点" + "\n" + "是否强制" + message,
            DialogUtils.getConfirmDialog(activity, getResources().getString(R.string.activity_inventory_item__position_is_still) + (allSize - submitSize) + getResources().getString(R.string.activity_inventory_item_no_stock_taking) + "\n" +getResources().getString(R.string.activity_inventory_item_whether_or_not_mandatory) + message,
                    new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    switch (type) {
                        case TYPE_BACK:
                            finish();
                            break;
                        case TYPE_CHANGE:
                            getData(activity, querybean);
                            break;
                    }
                }
            }).show();
        }


//        if (imrb.getMaterielList().size() > 0) {
//            InventoryManageRequest.updateItems(activity, imrb, new GsonBeanListener<InventoryRespBean>() {
//                @Override
//                public void onSuccess(InventoryRespBean bean) {
//                    if (bean.getData().getCode().equals(RequestConstant.BEAN_CODE_SUCCESS)) {
//                        switch (type) {
//                            case TYPE_BACK:
//                                finish();
//                                break;
//                            case TYPE_CHANGE:
//                                getData(activity, querybean);
//                                break;
//                        }
//                    } else {
//                        Utils.middleToast(activity, bean.getData().getMsg());
//                    }
//                }
//            });
//        } else {
//            switch (type) {
//                case TYPE_BACK:
//                    finish();
//                    break;
//                case TYPE_CHANGE:
//                    getData(activity, querybean);
//                    break;
//            }
//        }
    }

    private void changeAndSet(Context context, int type) {
        String checkResult = check();
        if (checkResult == null) {
            String numberStr = number.getText().toString();
            item.setNumber(numberStr);
            switch (type) {
                case TYPE_ADD:
                    index++;
                    break;
                case TYPE_REDUCE:
                    index--;
                    break;
            }
            load();
        } else {
            DialogUtils.getConfirmDialog(context, checkResult + "\n" + getResources().getString(R.string.activity_inventory_item_have_a_forced_switch), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    switch (type) {
                        case TYPE_ADD:
                            index++;
                            break;
                        case TYPE_REDUCE:
                            index--;
                            break;
                    }
                    load();
                }
            }).show();
        }
    }

    private boolean findMaterielCode(String materielCode) {
        for (int i = 0; i < items.size(); i++) {
            InventoryOrdinaryMaterieBean.DataBean.ItemListBean materielItem = items.get(i);
            if (materielItem.getMat_code().equals(materielCode)) {
                index = i;
                return true;
            }
        }
        return false;
    }

}
